package cn.com.bob.library.service.impl;

import cn.com.bob.library.entity.Book;
import cn.com.bob.library.entity.Borrow;
import cn.com.bob.library.mapper.BookMapper;
import cn.com.bob.library.service.BookService;
import cn.com.bob.library.service.BorrowService;
import cn.com.bob.library.service.ex.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.com.bob.library.entity.User;
import cn.com.bob.library.service.UserService;
import cn.com.bob.library.mapper.UserMapper;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author 12948
* @description 针对表【user】的数据库操作Service实现
* @createDate 2023-06-30 08:27:12
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BorrowService borrowService;

    @Autowired
    private BookMapper bookMapper;

    /**
     * 对用户进行添加操作
     * @param :
     * @return Int
     */
    @Override
    public Integer addUser(User user,String createUsername) {
        //查询该用户名查询该用户是否存在
        User username = userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if(username != null){
            //用户存在
            throw new UserExistException("用户已经存在");
        }
        //用户不存在，执行插入操作
        user.setCreateUsername(createUsername);
        user.setCreateTime(new Date());
        int rows = userMapper.insert(user);

        return rows;
    }

    /**
     * 根据用户名删除用户
     * @param username:
     * @return Integer
     */
    @Override
    public Integer deleteUserByUsername(String username) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username",username));
        //检查该用户是否还借者书
        List<Borrow> borrow = borrowService.getAllBorrowByUserId(user.getUserId());
        Iterator<Borrow> iterator = borrow.iterator();
        while (iterator.hasNext()) {
            Borrow next = iterator.next();
            if(next.getQuantity() > 0){
                throw new BookNotBackException("该用户还有书籍未归还，请先联系用户归还书籍。");
            }
        }
        int rows = userMapper.delete(new QueryWrapper<User>().eq("user_id",user.getUserId()));
        System.out.println(rows);
        return rows;
    }

    /**
     * 根据用户名更新用户信息
     * @param user:
     * @return Integer
     */
    @Override
    public Integer updateUserByUsername(User user,String username) {
        System.out.println(user);
        user.setModifyUsername(username);
        user.setModifyTime(new Date());
        int rows = userMapper.update(user,new QueryWrapper<User>().eq("user_id",user.getUserId()));
        System.out.println(rows);
        return rows;
    }

    /**
     * 查询所有用户返回list集合
     * @param :
     * @return List<User>
     */
    @Override
    public List<User> queryAllUsers() {
        return userMapper.selectList(null);
    }

    /**
     * 查询所有的普通用户
     * @param :
     * @return List<User>
     */
    @Override
    public List<User> queryAllNormalUsers() {
        return userMapper.selectList(new QueryWrapper<User>().eq("user_permission", 0));
    }
    /**
     * 查询所有的图书管理员
     * @param :
     * @return List<User>
     */
    @Override
    public List<User> queryAllBookManagers() {
        return userMapper.selectList(new QueryWrapper<User>().eq("user_permission", 1));
    }
    /**
     * 查询所有的顶层管理员
     * @param :
     * @return List<User>
     */
    @Override
    public List<User> queryAllManagers() {
        return userMapper.selectList(new QueryWrapper<User>().eq("user_permission", 2));
    }

    /**
     * 用户登录
     * @param username:
     * @param password:
     * @return User
     */
    @Override
    public User login(String username,String password) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if(user == null){
            throw new UserNotExistException("用户名不存在");
        }
        if(!user.getPassword().equals(password)){
            throw new PwdWrongException("密码错误");
        }
        return user;
    }

    /**
     * 获取某用户的借阅的所有图书
     * @param userId:
     * @return List<Book>
     */
    @Override
    public List<Book> getBorrowBooks(Integer userId) {
        List<Borrow> list = borrowService.getAllBorrowByUserId(userId);
        List<Book> books = new ArrayList<>();
        Iterator<Borrow> iterator = list.iterator();
        while (iterator.hasNext()) {
            Borrow borrow =  iterator.next();
            if(borrow.getQuantity() > 0){
                Integer bookId = borrow.getBookId();
                books.add(bookMapper.selectOne(new QueryWrapper<Book>().eq("book_id",bookId)));
            }

        }
        return books;
    }

    /**
     * 根据书名进行查询
     * @param title:
     * @param userId:
     * @return List<Book>
     */
    @Override
    public List<Book> getBorrowBooksByTitle(String title,Integer userId) {
        List<Book> books = getBorrowBooks(userId);
        List<Book> res = new ArrayList<>();
        Iterator<Book> iterator = books.iterator();
        while (iterator.hasNext()) {
            Book book =  iterator.next();
            if(book.getTitle().contains(title)){
                res.add(book);
            }

        }
        return res;
    }

    /**
     * 归还图书，触发器实行
     * @param userId:
     * @param bookId:
     * @return void
     */
    @Override
    public void returnBook(Integer userId, Integer bookId) {
        //1.在借阅关系表中减少某本书籍的借阅量时，图书表对应的书籍量应该增加，此处使用触发器来实现
        Borrow borrow = borrowService.getOne(new QueryWrapper<Borrow>().eq("user_id", userId).eq("book_id", bookId));
        borrow.setQuantity(borrow.getQuantity() - 1);
        borrow.setBackTime(new Date());
        //更新关系表,此时会触发器会执行。
        borrowService.update(borrow,new QueryWrapper<Borrow>().eq("user_id", userId).eq("book_id", bookId));
    }
}




